import os
import sys, re, time
import requests

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from api.mysql_format import weibo_format_to_mysql_api, bilibili_format_to_mysql_api,img_format_to_mysql_api
from flask import Flask, request
import urllib.parse
import json
import redis
import config
from api.bilibili_get_info import bilibili_get_page_info, bilibili_get_page_live
from api.miaopai_get_info import miaopai_get_page_info
from api.lofter_get_info import lofter_get_page_info

av_search = re.compile('av(\d+)')
pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_POST)  # host是redis主机，需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool, db=8)
app = Flask(__name__)


# 增加请求时间及增加缓存
def time_used(func):
    def warpper():
        time1 = time.time()
        url = request.args.get('url', '')
        if not url:
            return json.dumps({'code': '0'})
        if r.exists(url):
            return r.get(url)
        else:
            t = func()
            r.set(url, t, 10)
            return t

    return warpper


@app.route('/api')
@time_used
def get_info_by_url():
    get_url = request.args.get('url', '')
    url = urllib.parse.unquote(get_url)
    if 'weibo' in url:
        # try:
            # 拆分关键字
            key_word = url.split('?')[0].split('/')[-1]
            data = requests.get(f'https://m.weibo.cn/statuses/show?id={ key_word }').json()['data']
            # print(data)
            if data:
                return json.dumps({'code': '1', 'msg':'success', 'data': weibo_format_to_mysql_api(data)})
            else:
                return json.dumps({'code': '0'})
        # except TypeError as e:
        #     return json.dumps({'code': '0'})
    elif 'bilibili' in url:
        data=False
        if 'live' in url:
            # print('live')
            content = bilibili_get_page_live(url)
            content['pic_url'] = url
            content['video_ticket'] = ''
            content['type'] = 15
            data = bilibili_format_to_mysql_api(content)
        elif 'bangumi' in url:
            # print('bangumi')
            content = bilibili_get_page_info(url)
            content['pic_url'] = url
            content['type'] = 3
            content['video_ticket'] = ''
            data = bilibili_format_to_mysql_api(content)

        elif 'av' in url:
            # print('av')
            content = bilibili_get_page_info(url)
            content['pic_url'] = url
            content['type'] = 8

            # : "http://m.bilibili.com/video/av6266279.html"
            content['video_ticket'] = av_search.search(content["@id"]).group(1)
            data = bilibili_format_to_mysql_api(content)
        if data:
            return json.dumps({'code': '1', 'msg':'success', 'data': data})
        else:
            return json.dumps({'code': '0'})

    elif 'lofter' in url:
        content = lofter_get_page_info(url)
        content['url']=url
        content['video_ticket']=''
        content['video_link'] = ''

        content['type']=11
        content['media_type'] =1
        data=img_format_to_mysql_api(content)
        if data:
            return json.dumps({'code': '1', 'msg':'success','data': data})
        else:
            return json.dumps({'code': '0'})

    elif "miaopai" in url:
        content=miaopai_get_page_info(url)
        content['img']=[content['imgUrl']]
        content['url'] = url
        content['video_link'] =content['video']
        content['video_ticket'] =''
        content['type']=15
        content['media_type'] =2

        data=img_format_to_mysql_api(content)
        if data:
            return json.dumps({'code': '1', 'data': data})
        else:
            return json.dumps({'code': '0'})
    else:
        return json.dumps({'code': '0'})


if __name__ == '__main__':
    app.run('0.0.0.0', 9009)
